package com.baizhi.cmfz.realm;

import com.baizhi.cmfz.dao.AdminDao;
import com.baizhi.cmfz.entiy.Admin;
import com.baizhi.cmfz.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.*;

import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {


    private Logger logger= LoggerFactory.getLogger(AuthorRealm.class);

    @Autowired
    private AdminDao dao;
    @Autowired
    private RoleService roleService;


    /*
        authorization
            英[ˌɔːθəraɪˈzeɪʃn]
            n.	批准; 授权; 批准书; 授权书;
    */
    //获取授权信息 从数据库查询用户的角色以及权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取用户名
        String username= (String) principals.getPrimaryPrincipal();
        logger.debug("获取授权信息"+username);
        //获取用户角色信息
        Set<String> allRolesByUsername = roleService.getAllRolesByUsername(username);
        //获取用户的权限信息
        Set<String> allResourcesByUsername = roleService.getAllResourcesByUsername(username);
        //  将权限信息封装info
        if(allRolesByUsername!=null||allResourcesByUsername!=null){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setRoles(allRolesByUsername);
            info.setStringPermissions(allResourcesByUsername);
            return info;
        }
        return null;
    }


    //获取认证信息（从数据库查询账户是否存在）, controller层的subject.login方法自动调用
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取用户名
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username= (String) usernamePasswordToken.getPrincipal();
        logger.debug("进行认证："+usernamePasswordToken);
        //查询数据库
        Admin admin = dao.selectOne(new QueryWrapper<Admin>().eq("username", username));
        logger.debug("打印用户"+admin);
        //封装info
        if(admin!=null){
            /**
             * 用户名
             * 加密后的密码
             * 随机盐
             * 当前realm的名称
             */
            SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(
                    admin.getUsername(),
                    admin.getPassword(),
                    ByteSource.Util.bytes("1q2w3e"),
                    this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
